package com.jzo2o.orders.manager.service.impl;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.jzo2o.api.market.dto.request.CouponUseReqDTO;
import com.jzo2o.api.market.dto.response.CouponUseResDTO;
import com.jzo2o.common.utils.BeanUtils;
import com.jzo2o.orders.base.config.OrderStateMachine;
import com.jzo2o.orders.base.enums.OrderStatusEnum;
import com.jzo2o.orders.base.mapper.OrdersMapper;
import com.jzo2o.orders.base.model.domain.Orders;
import com.jzo2o.orders.base.model.dto.OrderSnapshotDTO;
import com.jzo2o.orders.manager.service.IOrdersSaveService;
import com.jzo2o.orders.manager.service.client.MarketClient;
import io.seata.spring.annotation.GlobalTransactional;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.math.BigDecimal;

/**
 * <p>
 * 下单服务类
 * </p>
 *
 * @author itcast
 * @since 2023-07-10
 */
@Slf4j
@Service
public class OrdersSaveServiceImpl extends ServiceImpl<OrdersMapper, Orders> implements IOrdersSaveService {

	@Resource
	private OrderStateMachine orderStateMachine;
	@Resource
	private IOrdersSaveService ordersSaveService;

	@Resource
	private MarketClient marketClient;

	@Override
	@Transactional(rollbackFor = Exception.class)
	public void saveOrder(Orders orders) {
		save(orders);
		Long ordersId = orders.getId();

		// 获取订单最新数据
		orders = this.getById(ordersId);
		/*
		 * 启动订单状态机
		 *
		 * Long dbShardId ：分库ID
		 * String bizId ：订单ID
		 * StatusDefine statusDefine ：订单状态定义（默认 NO_PAY，可省略）
		 * T bizSnapshot ：订单快照
		 */
		OrderSnapshotDTO orderSnapshotDTO = BeanUtils.toBean(orders, OrderSnapshotDTO.class);
		// 启动订单状态机
		orderStateMachine.start(orders.getUserId(), ordersId.toString(), OrderStatusEnum.NO_PAY, orderSnapshotDTO);
	}

	/**
	 * 下单并添加优惠券
	 *
	 * @param orders   订单信息
	 * @param couponId 优惠卷ID
	 * @return:
	 */
	@Override
	@GlobalTransactional(rollbackFor = Exception.class)
	public void addWithCoupon(Orders orders, Long couponId) {
		CouponUseReqDTO couponUseReqDTO = new CouponUseReqDTO();
		couponUseReqDTO.setId(couponId);
		couponUseReqDTO.setOrdersId(orders.getId());
		couponUseReqDTO.setTotalAmount(orders.getTotalAmount());
		CouponUseResDTO couponUseResDTO = marketClient.useCoupon(couponUseReqDTO);

		// 优惠金额
		orders.setDiscountAmount(couponUseResDTO.getDiscountAmount());
		// 计算实付金额
		BigDecimal realPayAmount = orders.getTotalAmount().subtract(orders.getDiscountAmount());
		orders.setRealPayAmount(realPayAmount);
		// 保存订单
		ordersSaveService.saveOrder(orders);

		// 测试全局事务回滚
		// int i = 1 / 0;
	}
}
